package com.herr.springboot.data.redis.jedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPool {
	public static RedisPool redisClientPool = getInstance();

	public static JedisPool jedisPool;

	public static synchronized RedisPool getInstance() {
		if (null == redisClientPool) {
			redisClientPool = new RedisPool();
		}
		return redisClientPool;
	}

	public RedisPool() {
		if (null == jedisPool) {
			init();
		}
	}

	private void init() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //控制一个pool可分配多少个jedis实例，通过pool.getResource()来获取；
        //如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
		jedisPoolConfig.setMaxTotal(10);
		jedisPoolConfig.setTestWhileIdle(false);
		jedisPoolConfig.setTimeBetweenEvictionRunsMillis(1000L);
		// 最大能够保持空闲状态的对象数
		jedisPoolConfig.setMaxIdle(10);
		// 超时时间
		jedisPoolConfig.setMaxWaitMillis(1000);
		// 在borrow一个jedis实例时，是否提前进行alidate操作；如果为true，则得到的jedis实例均是可用的；
		jedisPoolConfig.setTestOnBorrow(false);
		// 在还会给pool时，是否提前进行validate操作
		jedisPoolConfig.setTestOnReturn(false);
		String host = "127.0.0.1";
		int port = 6379;
		int timeout = 60000;
		String auth = null;
		if(null!=auth){
			jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, auth);
		}else{
			jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
		}
		
	}

    public synchronized static Jedis getJedis(int db_index) {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
				System.out.println(resource);
                resource.select(db_index);
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

	public synchronized static Jedis getJedis(int db_index,String uuid) {
		try {
			if (jedisPool != null) {
				Jedis resource = jedisPool.getResource();
				System.out.println(uuid +":"+ resource);
				resource.select(db_index);
				return resource;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
